<?php
include_once('simple_html_dom.php');
include_once('common.php');
include_once('sqlcommon.php');
include_once('kqxsvn.php');
include_once('kqxsday.php');
include_once('kqxsminhngoc.php');
function crawl($date,$type){
	$dayOfWeek=$date->format("N");
	$lotteryList = getLotteryByDay($dayOfWeek, $type);

	foreach($lotteryList as $lottery){

		echo "Crawling result for ". convert_vi_to_en($lottery['name']) . "." . $lottery['type'] . ". Date: ".$date->format("Y-m-d")."<br/>";
		$kqMinhNgoc=new KqxsMinhNgoc($lottery['url1']);
		$resultKqMinhNgoc = $kqMinhNgoc->crawl();

		if($resultKqMinhNgoc['open_date']!=$date->format('Y-m-d'))
		{
			echo "There is no result of ".convert_vi_to_en($lottery['name'])."<br/>";
			continue;
		}

		// Only compare data for MN & MT
		if($lottery['type']!='MB')
		{
			$kqvn = new KqxsVn($lottery['url']);
			$resultKqvn = $kqvn->crawl();

			$kqday = new Kqxsday($lottery['url2']);
			$resultKqday = $kqday->crawl();

			$equal1 = equal_result($resultKqvn,$resultKqday);
			$equal2 = equal_result($resultKqvn,$resultKqMinhNgoc);

			if($equal1 && $equal2)
			{
				insertLotteryResult($lottery["id"],$resultKqMinhNgoc );
				echo "Successful to crawl result of ". convert_vi_to_en($lottery['name']) ."<br/>";
			}
			else
			{
				$message ="Ket qua cua xo so ". convert_vi_to_en($lottery["name"]). " co van de";
				$message .=$equal1 ? ". KQVN != KQDay":"";
				$message .=$equal2 ? ". KQVN != KQDay":"";

				echo $message."<br/>";
			}
		}
		else{
			echo "Only get data from ". $lottery['url1']."<br/>";
			insertLotteryResult($lottery["id"],$resultKqMinhNgoc );
			echo "Successful to crawl result of ". convert_vi_to_en($lottery['name']) ."<br/>";
		}


	}
}
$date = isset($_REQUEST['open_date'])?date_create_from_format('Y-m-d',$_REQUEST['open_date']):(new DateTime());
crawl($date,'MN');
crawl($date,'MT');
crawl($date,'MB');
echo "<br/>Finish";
?>